package tgc.edu.xzy.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import tgc.edu.xzy.custom.AjaxResult;
import tgc.edu.xzy.custom.JpgridUtils;
import tgc.edu.xzy.entity.Accredit;
import tgc.edu.xzy.entity.SysUser;
import tgc.edu.xzy.form.AccreditForm;
import tgc.edu.xzy.security.UserUtils;
import tgc.edu.xzy.service.ImpowerService;

@Controller
@RequestMapping(value="/accredit")
public class AccreditController {
	@Autowired
	private ImpowerService impowerService;
	@Autowired
	private UserUtils userUtils;
	
	@RequestMapping(value="/all")
	public String all() {
		return "system/accreditgl";
	}
	
	@RequestMapping(value="/list")
	@ResponseBody
	public Object list(AccreditForm form) {
		Pageable pageable = form.buildPageable();
		Page<Accredit> page = null;
		if(form.getId() == null) {
			page = impowerService.findAll(pageable);			
		}else {
			page = impowerService.findAll(form.buildSpes(), pageable);
		}
		HashMap<String , Object> result = JpgridUtils.getPageResult(page);
		return result;
	}
	
	@RequestMapping(value="/save")
	@ResponseBody
	public Object save(Accredit model) throws ParseException {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date utilDate = sdf.parse(model.getBeginDate());
		Date newDate = stepMonth(utilDate, model.getMonth());
		model.setOverDate(newDate);
		impowerService.save(model);
		return AjaxResult.build(true, "OK");
	}

	private Date stepMonth(Date sourceDate, Integer month) {
        Calendar c = Calendar.getInstance();
        c.setTime(sourceDate);
        c.add(Calendar.MONTH, month);
		return c.getTime();
	}
	
	@RequestMapping(value="zh_all")
	public String zh_all() {
		return "LesseeAdmin/accredit_all";
	}
	
	@RequestMapping(value="list1")
	@ResponseBody
	public Object list1(AccreditForm form) {
		SysUser user = userUtils.getUser();
		Pageable pageable = form.buildPageable();
		Page<Accredit> page = null;
		System.out.println(user.getId());
		if(form.getId() == null) {
			page = impowerService.findByLesseeLesseeAdminId(user.getId(), pageable);			
		}else {
			page = impowerService.findByLesseeLesseeAdminId(user.getId(), form.buildSpes(), pageable);
		}
		HashMap<String , Object> result = JpgridUtils.getPageResult(page);
		return result;
	}
}
